package org.servlet;

import org.domain.Account;
import org.domain.Product;
import org.service.AccountService;
import org.service.CatalogService;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SignOnServlet extends HttpServlet {
    private static final String MAIN = "/WEB-INF/JSP/catalog/Main.jsp";
    private static final String SIGNON = "/WEB-INF/JSP/account/SignonForm.jsp";
    private AccountService accountService;
    private CatalogService catalogService;
    private Account account = null;
    private List<Product> myList = new ArrayList<Product>();
    private boolean authenticated = false;;
    private String username;
    private String password;

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        username = (String)session.getAttribute("username");
        password = (String)session.getAttribute("password");

        session.setAttribute("username",username);
        session.setAttribute("password",password);
        request.getRequestDispatcher(SIGNON).forward(request,response);
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        catalogService = new CatalogService();
        accountService = new AccountService();
        username = request.getParameter("username");
        password = request.getParameter("password");
        account = new Account();
        account = accountService.getAccount(username, password);


        String Code = (String)session.getAttribute("randCheckCode");
        String inputCode = request.getParameter("checkCode");


        if (account == null) {
            request.setAttribute("error1", "Invalid username or password. Signon failed.");
            request.getRequestDispatcher(SIGNON).forward(request, response);
        }
        else if(Code.equals(inputCode))
            {
            account.setPassword(null);
            myList = catalogService.getProductListByCategory(account.getFavouriteCategoryId());
            authenticated = true;

            HttpSession s = request.getSession();
            s.setAttribute("account", account);
            s.setAttribute("myList", myList);
            s.setAttribute("authenticated", authenticated);
            request.getRequestDispatcher(MAIN).forward(request,response);
        }
        else
        {
            request.setAttribute("error1", "Please input a right Code!");
            request.getRequestDispatcher(SIGNON).forward(request, response);
        }
    }

}
